<?php

namespace Ignus\View\Node\Expression;

use Ignus\View\Node\Expression;
use Ignus\View\Compiler;
use Ignus\View\NodeInterface;
use Ignus\View\FilterInterface;
use Ignus\View\Error\Syntax;

class Name extends Expression
{
    public function __construct($name, $lineno)
    {
        parent::__construct(array(), array('name' => $name, 'output' => false), $lineno);
    }

    public function compile(Compiler $compiler)
    {
        static $specialVars = array(
            '_self'    => '$this',
            '_context' => '$context',
            '_charset' => '$this->env->getCharset()',
        );

        $name = $this->getAttribute('name');

        if ($this->hasAttribute('is_defined_test')) {
            if (isset($specialVars[$name])) {
                $compiler->repr(true);
            }
            else {
                $compiler->raw('array_key_exists(')->repr($name)->raw(', $context)');
            }
        }
        elseif (isset($specialVars[$name])) {
            $compiler->raw($specialVars[$name]);
        }
        elseif ($this->getAttribute('output')) {
            $compiler
                ->addDebugInfo($this)
                ->write('if (isset($context[')
                ->string($name)
                ->raw("])) {\n")
                ->indent()
                ->write('echo $context[')
                ->string($name)
                ->raw("];\n")
                ->outdent()
                ->write("}\n");
        }
        else {
            $compiler
                ->raw('$this->getContext($context, ')
                ->string($name)
                ->raw(')');
        }
    }
}
